﻿namespace LuckyAssetManagerContrib.FileCache
{
	using System.Collections.Generic;
	using System.Xml;
	using System.Xml.Schema;
	using System.Xml.Serialization;

	/// <summary>
	/// File cache registry
	/// </summary>
	[XmlRoot("registry")]
	public sealed class AssetFileCacheRegistry : Dictionary<string, AssetFileCacheItem>, IXmlSerializable
	{
		public XmlSchema GetSchema()
		{
			return null;
		}

		public void ReadXml(XmlReader reader)
		{
			var valueSerializer = new XmlSerializer(typeof(AssetFileCacheItem));

			if (reader.IsEmptyElement)
			{
				return;
			}

			reader.ReadStartElement("registry");

			while (reader.NodeType != XmlNodeType.EndElement)
			{
				reader.ReadStartElement("entry");

				reader.ReadStartElement("key");
				string key = reader.ReadString();
				reader.ReadEndElement();

				reader.ReadStartElement("value");
				var value = (AssetFileCacheItem)valueSerializer.Deserialize(reader);
				reader.ReadEndElement();
				Add(key, value);

				reader.ReadEndElement();
			}

			reader.ReadEndElement();
		}

		public void WriteXml(XmlWriter writer)
		{
			var valueSerializer = new XmlSerializer(typeof(AssetFileCacheItem));

			foreach (string key in Keys)
			{
				writer.WriteStartElement("entry");

				writer.WriteStartElement("key");
				writer.WriteValue(key);
				writer.WriteEndElement();

				writer.WriteStartElement("value");
				AssetFileCacheItem value = this[key];
				valueSerializer.Serialize(writer, value);
				writer.WriteEndElement();

				writer.WriteEndElement();
			}
		}
	}
}
